using System;
using UnityEngine;

namespace Framework
{
    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        private static T _instance;
        public static T Instance => GetInstance();

        // Just disable Rider performance warning.
        // Why this? No why, it works.
        private static T GetInstance()
        {
            if (!_instance) _instance = FindFirstObjectByType<T>();
            if (_instance) return _instance;
            throw new Exception($"Trying to get singleton instance {nameof(T)} before initialization.");
            _instance = new GameObject($"Singleton Object {typeof(T).Name}").AddComponent<T>();
            return _instance;
        }

        /// <summary>是否跨场景保留</summary>
        protected virtual bool flagCrossScenes => false;
        /// <summary>新对象是否覆盖旧对象</summary>
        protected virtual bool flagOverride => false;
        protected virtual void Awake()
        {
            if (_instance == null)
            {
                _instance = this as T;
                if (flagCrossScenes) DontDestroyOnLoad(gameObject);
            }
            else if (_instance != null && _instance != this)
            {
                if (!flagOverride) Destroy(gameObject);
                else
                {
                    Destroy(_instance.gameObject);
                    _instance = this as T;
                }
            }
        }

        protected virtual void OnDestroy()
        {
            if (_instance == this) _instance = null;
        }
    }
}